package com.qingzhou.gateway.config;

import com.qingzhou.gateway.config.properties.GatewayProperties;
import com.qingzhou.common.security.impl.AuthProcessorImpl;
import org.noear.solon.annotation.*;
import org.noear.solon.auth.AuthAdapter;
import org.noear.solon.auth.AuthRule;
import org.noear.solon.auth.impl.AuthRuleImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * 网关配置
 * @author xm
 */
@Configuration
public class GatewayConfig {

    /**
     * 注入配置
     * @param gatewayProperties
     * @return
     */
    @Bean
    public GatewayProperties gatewayProperties(@Inject("${qingzhou.gateway}") GatewayProperties gatewayProperties) {
        return gatewayProperties;
    }

    /**
     * 鉴权处理
     * @return
     */
    @Bean
    @Condition(onClass = GatewayProperties.class)
    public AuthAdapter authAdapter(GatewayProperties gatewayProperties) {
        return new AuthAdapter()
                // 添加规则
                .addRules(getRules(gatewayProperties))
                // 设定鉴权处理器
                .processor(new AuthProcessorImpl());
    }

    /**
     * 定义规则
     * @return
     */
    private List<AuthRule> getRules(GatewayProperties gatewayProperties) {
        List<AuthRule> list = new ArrayList<>();

        // 所有请求，校验 IP白名单
        AuthRuleImpl ipRule = new AuthRuleImpl();
        AuthRule verifyIp = ipRule.include("/**").verifyIp();
        list.add(verifyIp);

        // 所有请求，排除白名单，校验登录
        AuthRuleImpl loginRule = new AuthRuleImpl();
        loginRule.include("/**");
        for (String path : gatewayProperties.getWhites()) {
            loginRule.exclude(path);
        }
        AuthRule verifyLogined = loginRule.verifyLogined();
        list.add(verifyLogined);

        return list;
    }

}
